package com.catmiw.stock2013.util;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateTool {
	public static int toInt(Date date){
		if (date==null)
			return 0;
		return Integer.parseInt(dateToString(date,"yyyyMMdd"));
	}
	
	public static int daysBetween(Date from,Date to){
		from=toDate(toInt(from));
		to=toDate(toInt(to));
		
		int days = (int) ((to.getTime() - from.getTime())/(24 * 60 * 60 * 1000)); 

		return days; 
	}
	
	public static int getDayOfWeek(Date date){
		Calendar c=Calendar.getInstance();
		c.setTime(date);
		
		return c.get(Calendar.DAY_OF_WEEK);
	}
	
	public static Date dateAfterDays(Date date,int days){
		Calendar cal=Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.DATE, days);
		return cal.getTime();
	}
	
	public static Date toDate(int ymd){
		if (ymd<19500101||ymd>99991231)
			return null;
		
		String s=String.valueOf(ymd);
		
		return toDate(s);
	}
	
	public static Date toDate(String ymd){
		if (ymd==null||ymd.length()<8||ymd.length()>10)
			return null;
		
		StringBuilder sb=new StringBuilder();
		for(char c:ymd.toCharArray()){
			if (c>='0'&&c<='9')
				sb.append(c);
		}
		String t=sb.toString();
		if (t.length()!=8)
			return null;
		
		String temp[]=new String[3];
		temp[0]=t.substring(0,4);
		temp[1]=t.substring(4,6);
		temp[2]=t.substring(6,8);
		
		Calendar c=Calendar.getInstance();
		c.clear();

		c.set(Integer.parseInt(temp[0]),Integer.parseInt(temp[1])-1,Integer.parseInt(temp[2]));
		return c.getTime();
	}
	
	public static int lastDayOfMonth(Date date){
		Calendar c=Calendar.getInstance();
		c.setTime(date);
		return c.getActualMaximum(Calendar.DAY_OF_MONTH);   

	}
	public static Date lastDayOfMonthByDate(Date date){
		Calendar c=Calendar.getInstance();
		c.setTime(date);
		c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH));
		return c.getTime();   
	}

	public static int[] getYMD(Date date){
		Calendar c=Calendar.getInstance();
		c.setTime(date);
		int ymd[]=new int[3];
		ymd[0]=c.get(Calendar.YEAR);
		ymd[1]=c.get(Calendar.MONTH)+1;
		ymd[2]=c.get(Calendar.DAY_OF_MONTH);
		return ymd;
	}
	public static String dateToString(Date date,String format){
		DateFormat sdf=new SimpleDateFormat(format);
		return sdf.format(date);
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println(dateToString(dateAfterDays(new Date(),10),"yyyy-MM-dd"));
		System.out.println(daysBetween(new Date(),toDate("20091129")));
		
	}

}
